package com.weiawei.net;

import com.weiawei.Model.Chess;
import com.weiawei.Model.TimeThread;
import com.weiawei.ui.ChessBoard;
import com.weiawei.ui.PVPChessBoard;
import com.weiawei.ui.PVPMainBoard;

import java.io.IOException;

public class RoleChoose implements Runnable {
    private PVPMainBoard mainBoard;
    private PVPChessBoard chessBoard;
    private NetContainer netContainer;
    private String message;

    /**
     * 执棋选择线程的构造函数
     *
     * @param mainBoard    邮箱主界面
     * @param netContainer 用户端或服务端
     */
    public RoleChoose(PVPMainBoard mainBoard, NetContainer netContainer) {
        this.mainBoard = mainBoard;
        this.chessBoard = mainBoard.getChessBoard();
        this.netContainer = netContainer;
    }

    @Override
    public void run() {
        try {
            netContainer.getOut().writeUTF("Ready");
            message = netContainer.getIn().readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            mainBoard.getProcessLabel().setText("准备判断错误");
        }
        if (message.equals("Ready")) {
            mainBoard.getButtonStart().setText("正在游戏");
            //   选色
            try {
                if (netContainer instanceof Server) {
                    mainBoard.getChessBoard().setRoleDialog();
                    netContainer.getOut().writeUTF(mainBoard.getChessBoard().getRole() + "");
                } else {
                    message = netContainer.getIn().readUTF();
                    if (message.equals(Chess.black + "")) {
                        chessBoard.setRole(Chess.white);
                        chessBoard.setOpponentRole(Chess.black);
                    } else {
                        chessBoard.setRole(Chess.black);
                        chessBoard.setOpponentRole(Chess.white);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                mainBoard.getProcessLabel().setText("执棋选择错误");
            }
            //    游戏正式开始
            mainBoard.setTimeThread(new TimeThread(mainBoard.getTimeCountLabel()));
            mainBoard.getTimeThread().start();
            mainBoard.getChessBoard().setResult(ChessBoard.GAME_START);
            mainBoard.getButtonBack().setEnabled(true);
            //    黑棋起手
            if (mainBoard.getChessBoard().getRole() == Chess.white) {
                mainBoard.getProcessLabel().setText("等待对方落棋");
                new Thread(new PlayChess(this.mainBoard, this.mainBoard.getNetContainer())).start();
                chessBoard.setClickable(false);
            } else {
                mainBoard.getProcessLabel().setText("轮到你了");
                chessBoard.setClickable(true);
            }
        } else if (message.equals("Exit")) {
            mainBoard.getProcessLabel().setText("对方已退出游戏");
        }
    }
}
